package edu.yuhf.dao;

import com.yuhf.dbutils.JdbcTemplate;
import com.yuhf.dbutils.ParameterMap;
import edu.yuhf.dao.iface.AchievementDao;
import lombok.extern.log4j.Log4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Log4j
public class AchievementJdbcDaoImpl implements AchievementDao {

    private AchievementJdbcDaoImpl(){}

    public static AchievementDao factory(){
        return new AchievementJdbcDaoImpl();
    }

    @Override
    public int deleteStudentAchievement(int studentId) {
        String sql="delete from achievement where student_id=?";
        return JdbcTemplate.update(sql,studentId);
    }

    @Override
    public List<Map<String, Object>> queryAchievement(ParameterMap parameterMap) {
        StringBuilder sb=new StringBuilder("select si.sno,si.name,s.subject_name,a.score from student_info si inner join achievement a on si.id=a.student_id inner join subject s on a.subject_id=s.id where 1=1");
        var map=parameterMap.getMap();
        List<Object> list = new ArrayList();
        if(null!=map && map.size()!=0){
            map.keySet().forEach(key->{
                if(ParameterMap.NAME_EQUALS.equals(key)){
                    sb.append(" and ").append(key.substring(0,key.indexOf("_"))).append("=?");
                    list.add(map.get(key));
                }
                if("subject".equals(key)){
                    sb.append(" and subject_name=?");
                    list.add(map.get(key));
                }
                if("score_between".equals(key)){
                    sb.append(" and score between ? and ?");
                    var temp=((String)map.get(key)).split(",");
                    list.add(Integer.valueOf(temp[0]));
                    list.add(Integer.valueOf(temp[1]));
                }
            });
        }
        log.debug(sb.toString());
        return JdbcTemplate.query(sb.toString(),list.toArray());
    }
}
